package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 发送验证码
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String>  sendMsg (@RequestBody User user , HttpSession session){
        // 获取手机号

        String phone = user.getPhone();

        if (StringUtils.isNotEmpty(phone)){
            //生成验证码
            String code = ValidateCodeUtils.generateValidateCode(6).toString();
            log.info("code:{}",code);

            //将生成的验证码发送到session上保存

            session.setAttribute(phone,code);
            return R.success("验证码发送成功");
        }
        return R.error("验证码发送失败");
    }

    /**
     *手机验证码登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public  R<User> login (@RequestBody  Map map,HttpSession session){
        log.info(map.toString());

        //获取手机号和验证码
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

        //session中的验证码

        Object codeSession= session.getAttribute(phone);

        //判断验证码是否相同
        if(codeSession != null && codeSession.equals(code)){

            //  对比成功，登录成功
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(queryWrapper);
            // 如果user 不存在，自动注册
            if(user == null){
                user = new User();

                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            //将手机用户信息保存在session上

            session.setAttribute("user",user.getId());

            return R.success(user);
        }
        return R.error("登陆失败，请检查手机号或者验证码是否正确");
    }


}